<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" size="small" :inline="true">
            <el-form-item label="算例名称" prop="originalName">
              <el-input v-model="queryParams.originalName" placeholder="请输入算例名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="展示名称" prop="displayName">
              <el-input v-model="queryParams.displayName" placeholder="请输入展示名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="分析类型" prop="analysisType">
              <el-input v-model="queryParams.analysisType" placeholder="请输入分析类型" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="search" @click="handleQuery">查询</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button size="small" v-hasPermi="['system:oss:upload']" type="primary" plain icon="Upload"
              @click="addArithmeticExample">新增算例</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button size="small" v-hasPermi="['system:oss:remove']" type="danger" plain icon="Delete"
              :disabled="multiple" @click="handleDelete()">
              删除
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getListdata"></right-toolbar>
        </el-row>
      </template>

      <el-table v-if="showTable" v-loading="loading" :data="tableData" :header-cell-class-name="handleHeaderClass"
        @selection-change="handleSelectionChange" @header-click="handleHeaderCLick">
        <el-table-column type="selection" width="55" align="left" />
        <el-table-column label="文档名称" align="left" prop="originalName" show-overflow-tooltip />
        <!-- <el-table-column label="服务" align="left" prop="service" show-overflow-tooltip/>
        <el-table-column label="文件名" align="left" prop="fileName" show-overflow-tooltip/> -->
        <el-table-column label="算例类型" align="left" prop="calculationExampleType" width="200" show-overflow-tooltip />
        <el-table-column label="分析类型" align="left" prop="analysisType" show-overflow-tooltip />
        <el-table-column label="算法名称" align="left" prop="displayName" show-overflow-tooltip />
        <el-table-column label="操作" align="left" width="180">
          <template #default="scope">
            <!-- <el-tooltip content="详情" placement="top">
              <el-button v-hasPermi="['system:oss:download']" link type="primary" icon="Document" @click="handleDetail(scope.row)"></el-button>
            </el-tooltip> -->
            <el-tooltip content="预览" placement="top">
              <el-button size="small" link type="primary" icon="View" @click="view(scope.row)">预览</el-button>
            </el-tooltip>
            <el-tooltip content="下载" placement="top">
              <el-button size="small" v-hasPermi="['system:oss:download']" link type="primary" icon="Download"
                @click="handleDownload(scope.row)">下载</el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button size="small" v-hasPermi="['system:oss:remove']" link type="primary" icon="Delete"
                @click="handleDelete(scope.row)">删除</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
        :total="total" layout="total, sizes, prev, pager, next, jumper" @pagination="getListdata" />
    </el-card>
    <!-- 添加或修改OSS对象存储对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="420px" append-to-body>
      <el-form ref="ossFormRef" :model="form" :rules="rules" label-width="80px" inline>
        <!-- <el-form-item label="算例类型" style="width: 672px" prop="calculationExampleType">
          <el-input v-model="form.calculationExampleType" />
        </el-form-item> -->
        <el-form-item label="展示名称" prop="id">
          <!-- <el-input v-model="form.displayName" />
          <el-select v-model="form.displayName" ></el-select> -->
          <el-select v-model="form.displayName" filterable remote reserve-keyword placeholder="请输入关键词"
            :remote-method="remoteMethod" :loading="loading" @change="analysisChange">
            <el-option v-for="item in analysisList" :key="item._id" :label="item.displayName" :value="item.displayName">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分析类型" prop="analysisType">
          <el-input disabled v-model="form.analysisType" />
        </el-form-item>
        <el-form-item label="上传文件" prop="file">
          <el-upload :before-upload="handleBeforeUpload" @change="handleChange" :on-remove="handleRemove"
            :file-list="fileList" :show-file-list="true" :auto-upload="false" :multiple="false" accept=".pdf,.doc,.docx"
            :limit="1" action="#">
            <el-button type="primary">选取文件</el-button>
            <div class="el-upload__tip">模型文件大小超过1GB,请走离线方式</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="viewDialog.visible" custom-class="full-screen" :fullscreen="false" :title="viewDialog.title"
      width="1200px" append-to-body>
      <ViewOffice v-if="viewDialog.visible" :srcUrl="viewInfo.url" :type="viewInfo.type" />
    </el-dialog>
  </div>
</template>

<script setup name="saveArithmeticExample" lang="ts">
import { ref, onMounted, nextTick, reactive } from 'vue';
import { listOss, delOss } from '@/api/system/oss';
import { OssForm, OssQuery, OssVO } from '@/api/system/oss/types';
import axios from 'axios';
import { getToken } from '@/utils/auth';
import { downloadArithmeticExample, getArithmeticExampleList, deleteArithmeticExample, saveArithmeticExample } from '@/api/arithmeticExample';
import { getList } from '@/api/algorithmLibrary';
import ViewOffice from '@/components/ViewOffice'
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const analysisList = ref([]);
const analysisListInit = ref([]);
const tableData = ref([]);
const showTable = ref(true);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const type = ref(0);
const previewListResource = ref(true);
const dateRangeCreateTime = ref<[DateModelType, DateModelType]>(['', '']);
const fileList = ref<any[]>([]);
const dialog = reactive<DialogOption>({
  visible: false,
  title: '新增算例'
});
const viewDialog = reactive<DialogOption>({
  visible: false,
  title: '算例库文件预览'
});
const submitFile = ref(null);
const viewInfo = reactive({
  url: '',
  type: ''
})
// 默认排序
const defaultSort = ref({ prop: 'createTime', order: 'descending' });

const ossFormRef = ref<ElFormInstance>();
const queryFormRef = ref<ElFormInstance>();

const initFormData = {
  file: undefined,
  id: undefined,
  displayName: undefined,
  calculationExampleType: undefined,
  analysisType: undefined
};
const data = reactive<PageData<OssForm, OssQuery>>({
  form: { ...initFormData },
  // 查询参数
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    originalName: '',
    displayName: '',
    analysisType: '',
  },
  rules: {
    displayName: [{ required: true, message: '展示名称不能为空', trigger: 'blur' }],
    analysisType: [{ required: true, message: '分析类型不能为空', trigger: 'blur' }],
  }
});

const { queryParams, form, rules } = toRefs(data);

// 算法枚举筛选
const getAnalysisData = (query) => {
  getList({
    'pageNum': 1,
    'pageSize': 20,
    isPublished: true,
    'displayName': query
  }).then(res => {
    loading.value = false;
    if (!query) {
      analysisList.value = res.rows;
      analysisListInit.value = res.rows;
    } else {
      analysisList.value = res.rows;
    }
  })
}
const remoteMethod = (query) => {
  if (query !== '') {
    loading.value = true;
    getAnalysisData(query)
  } else {
    analysisList.value = analysisListInit.value;
  }
}

const analysisChange = () => {
  // console.log('form', form)
  if (form.value.displayName) {
    form.value.analysisType = '';
    let fItem = analysisList.value.find(item => item.displayName === form.value.displayName)
    fItem && (
      form.value.analysisType = fItem.analysisType
    )
    console.log('fItem', fItem)
  }
}

// 新增算例
const addArithmeticExample = () => {
  getAnalysisData('');
  form.value = { ...initFormData };
  submitFile.value = null;
  fileList.value = [];
  dialog.visible = true
}

// 预览
const view = (row) => {
  const { calculationExampleType } = row;
  downloadArithmeticExample(row?.calculationExampleId).then(res => {
    if (res) {
      console.log(res);
      // const blob = new Blob([res], { type: 'application/octet-stream' });
      const blob = new Blob([res]);
      const url = window.URL.createObjectURL(blob);
      viewInfo.url = url;
      viewInfo.type = calculationExampleType;
      nextTick(() => {
        console.log(viewInfo.value);
        viewDialog.visible = true;
      })
      // 释放url
      // window.URL.revokeObjectURL(url);
    }

  })

}
// 查看详情
const handleDetail = () => { };
// 上传前校检格式和大小
const handleBeforeUpload = (file: any) => {
  // 校检文件大小
  const isLt = file.size / 1024 / 1024 < 1024;
  if (!isLt) {
    proxy?.$modal.msgError(`上传文件大小不能超过 1024 MB!`);
    return false;
  }
  return true;
};
const handleRemove = (file: any) => {
  fileList.value = [];
  form.value.file = null;
  form.value.modelName = '';
};
const handleChange = (file: any) => {
  submitFile.value = file;
  form.value.file = file;
  form.value.modelName = file.name;
  ossFormRef.value.validate();
};

/** 查询算例库列表 */
const getListdata = async () => {
  loading.value = true;
  const response = await getArithmeticExampleList(queryParams.value);
  tableData.value = response.rows;
  total.value = response.total;
  loading.value = false;
  showTable.value = true;
};
/** 取消按钮 */
function cancel() {
  dialog.visible = false;
  reset();
}
/** 表单重置 */
function reset() {
  form.value = { ...initFormData };
  ossFormRef.value?.resetFields();
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getListdata();
}
/** 重置按钮操作 */
function resetQuery() {
  showTable.value = false;
  dateRangeCreateTime.value = ['', ''];
  queryFormRef.value?.resetFields();
  queryParams.value.orderByColumn = defaultSort.value.prop;
  queryParams.value.isAsc = defaultSort.value.order;
  handleQuery();
}
/** 选择条数  */
function handleSelectionChange(selection: OssVO[]) {
  ids.value = selection.map((item) => item.calculationExampleId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  debugger
}
/** 设置列的排序为我们自定义的排序 */
const handleHeaderClass = ({ column }: any): any => {
  column.order = column.multiOrder;
};
/** 点击表头进行排序 */
const handleHeaderCLick = (column: any) => {
  if (column.sortable !== 'custom') {
    return;
  }
  switch (column.multiOrder) {
    case 'descending':
      column.multiOrder = 'ascending';
      break;
    case 'ascending':
      column.multiOrder = '';
      break;
    default:
      column.multiOrder = 'descending';
      break;
  }
  handleOrderChange(column.property, column.multiOrder);
};
const handleOrderChange = (prop: string, order: string) => {
  let orderByArr = queryParams.value.orderByColumn ? queryParams.value.orderByColumn.split(',') : [];
  let isAscArr = queryParams.value.isAsc ? queryParams.value.isAsc.split(',') : [];
  let propIndex = orderByArr.indexOf(prop);
  if (propIndex !== -1) {
    if (order) {
      //排序里已存在 只修改排序
      isAscArr[propIndex] = order;
    } else {
      //如果order为null 则删除排序字段和属性
      isAscArr.splice(propIndex, 1); //删除排序
      orderByArr.splice(propIndex, 1); //删除属性
    }
  } else {
    //排序里不存在则新增排序
    orderByArr.push(prop);
    isAscArr.push(order);
  }
  //合并排序
  queryParams.value.orderByColumn = orderByArr.join(',');
  queryParams.value.isAsc = isAscArr.join(',');
  getListdata();
};
/** 提交按钮 */
const submitForm = async () => {
  ossFormRef.value.validate((valid: any) => {
    if (!valid) {
      return false;
    } else {
      const formData = new FormData();
      const metadata = form.value;
      metadata.calculationExampleType = metadata.file?.name.slice(metadata.file?.name.lastIndexOf('.'));

      formData.append('file', submitFile?.value?.raw);
      formData.append('displayName', metadata?.displayName);
      formData.append('analysisType', metadata?.analysisType);
      formData.append('calculationExampleType', metadata?.calculationExampleType);
      // let VITE_APP_BASE_API = '/dev-api';
      // if (import.meta.env.MODE === 'production') {
      //   VITE_APP_BASE_API = '/prod-api';
      // }
      // axios
      //   .post(`${VITE_APP_BASE_API}/calculationExample/save`, formData, {
      //     headers: { 'Content-Type': 'multipart/form-data', 'Authorization': 'Bearer ' + getToken() }
      //   })
      saveArithmeticExample(formData).then((res) => {
        dialog.visible = false;
        fileList.value = [];
        delete metadata.file;
        proxy?.$modal.msgSuccess('新增成功');
        getListdata();
      });
    }
  });
};
/** 下载按钮操作 */
const handleDownload = (row: OssVO) => {
  proxy?.$download.oss(row.calculationExampleId, '/calculationExample/download/');
};
/** 删除按钮操作 */
const handleDelete = async (row?: OssVO) => {
  const modelIds = row?.calculationExampleId || ids.value;
  await proxy?.$modal.confirm(row?.calculationExampleId ? '是否确认删除算例为"' + row?.originalName + '"的数据项?' : '是否确认删除当前所选全部数据项?');
  loading.value = true;
  await deleteArithmeticExample(modelIds).finally(() => (loading.value = false));
  await getListdata();
  proxy?.$modal.msgSuccess('删除成功');
};

onMounted(() => {
  getListdata();
});
</script>
<style lang="scss" scoped>
:deep(.el-upload) {
  display: block;
}

.full-screen {
  overflow-y: auto;
}
</style>
